/**
 * HQLDefaultProvider.java
 * 卢晓峰
 * Email：lxf9601@gmail.com
 * QQ：297051898
 * Created by 2010-7-17
 */
package com.autoabacus.core.config.provider;

import java.util.List;

import javax.annotation.Resource;

import com.autoabacus.core.config.Config;
import com.autoabacus.core.config.ConfigQueryProvider;
import com.autoabacus.core.config.PageData;
import com.autoabacus.core.config.component.Table;
import com.autoabacus.core.config.persistence.PersistenceProvider;

/**
 * HQL生成提供程序
 * @author 卢晓峰
 */
public class HQLDefaultProvider implements ConfigQueryProvider {
	
	public static final String QUERY_SELECT = "select";
	public static final String QUERY_INSERT = "insert";
	public static final String QUERY_UPDATE = "update";
	public static final String QUERY_DELETE = "delete";
	
	/** 系统配置信息 */
	private Config config = null;
	private PersistenceProvider hibernateDao;
	
	/**
	 * 创建HQL语句
	 * @param querySource
	 * @return
	 */
	private String createHQL(QuerySource querySource) {
		Table table = config.getTables().get(querySource.getTableName());
		HQLCreator creator = HQLCreatorFactory.getCreator(querySource.getQueryCommand());		
		return creator.getHQL(table, querySource);
	}

	public void setConfig(Config config) {
		this.config = config;
	}
	
	@Resource
	public void setHibernateDao(PersistenceProvider hibernateDao) {
		this.hibernateDao = hibernateDao;
	}

	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.ConfigQueryHandler#queryList(com.autoabacus.core.config.provider.QuerySource)
	 */
	@Override
	public List<?> queryList(QuerySource querySource) {		
		return hibernateDao.queryList(createHQL(querySource));
	}

	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.ConfigQueryHandler#executeUpdate(com.autoabacus.core.config.provider.QuerySource)
	 */
	@Override
	public int executeUpdate(QuerySource querySource) {
		// 使用本地化处理
		if (querySource.getQueryCommand().equals(QUERY_INSERT))
			return hibernateDao.executeInsert(createHQL(querySource));
		else
			return hibernateDao.executeUpdate(createHQL(querySource));
	}

	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.ConfigQueryHandler#queryPage(com.autoabacus.core.config.provider.QuerySource, int, int)
	 */
	@Override
	public PageData queryPage(QuerySource querySource, int size, int page) {
		return hibernateDao.queryPage(createHQL(querySource), size, page);
	}

	/* (non-Javadoc)
	 * @see com.autoabacus.core.config.ConfigQueryHandler#queryObject(com.autoabacus.core.config.provider.QuerySource)
	 */
	@Override
	public Object queryObject(QuerySource querySource) {
		
		List<Class<?>> list = hibernateDao.queryList(createHQL(querySource));
		if (list.size() > 0)
			return list.get(0);
		else
			return null;
	}

}
